package com.acme.bankapp.domain.client;

import java.io.Serializable;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import com.acme.bankapp.domain.account.Account;
import com.acme.bankapp.domain.account.AccountExistsException;

@SuppressWarnings("serial")
public class Client implements Serializable {

	private Set<Account> accounts = new HashSet<>();
	private String name;
	private Gender gender;

	public Client(String name, Gender gender) {
		this.name = name;
		this.gender = gender;
	}
	
	public Client(String name, Gender gender, Account account) {
		this(name, gender);
		accounts.add(account);
	}
	
	public String getClientSalutation() {
		return String.format("%s %s", gender.getHonorific(), name);
	}
	
	public void addAccount(Account account) throws AccountExistsException {
		if (accounts.contains(account))
			throw new AccountExistsException(account);
		
		accounts.add(account);
	}
	
	public Set<Account> getAccounts() {
		return Collections.unmodifiableSet(accounts);
	}
	
	public int getAccountsCount() {
		return accounts.size();
	}
	
	public String toString() {
		return String.format("%s has %d accounts",
					this.getClientSalutation(),
					this.accounts.size());
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((gender == null) ? 0 : gender.hashCode());
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Client other = (Client) obj;
		if (gender != other.gender)
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}
	
	

}
